package com.bachelor.community.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
public class UserSupport {
    public Integer getCurrentUserId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        String token = StrUtil.removePrefix(requestAttributes.getRequest().getHeader("Authorization"), "Bearer ");
        JWT jwt = JWTUtil.parseToken(token);
        Integer userId = Convert.toInt(jwt.getPayload("user_id"));
        if (userId < 0) {
            throw new ServiceException("500", "非法用户！");
        }
        return userId;
    }
}
